package com.zhang.flink.exercise;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @title:
 * @author: zhangyifan
 * @date: 2022/11/28 10:17
 */
public class Example2 {
    public static void main(String[] args) throws Exception {
        // 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 获取数据源，处理数据逻辑
        env
                .socketTextStream("localhost", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] fields = value.split(" ");
                        for (String field : fields) {
                            out.collect(Tuple2.of(field, 1));
                        }

                    }
                })
                .keyBy(r -> r.f0)
                .process(new KeyedProcessFunction<String, Tuple2<String, Integer>, String>() {
                    // 定义状态变量，用来存储中间计算结果
                    private ValueState<Integer> acc;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        acc = getRuntimeContext().getState(
                                new ValueStateDescriptor<Integer>(
                                        "acc", Types.INT
                                )
                        );
                    }

                    @Override
                    public void processElement(Tuple2<String, Integer> value, KeyedProcessFunction<String, Tuple2<String, Integer>, String>.Context ctx, Collector<String> out) throws Exception {
                        if (acc.value() == null) {
                            acc.update(value.f1);
                        } else {
                            acc.update(value.f1 + acc.value());
                        }
                        out.collect(value.f0 + "->" + acc.value());
                    }
                })
                .print();


        // 执行任务
        env.execute();
    }
}
